import express from 'express';
import cors from 'cors';

const app = express();
const PORT = 3000;

// 允许跨域和解析JSON
app.use(cors());
app.use(express.json());

// 数码产品数据库
const phoneDatabase = {
    apple: ['iPhone 15 Pro', 'iPhone 15', 'iPhone 14', 'iPhone SE'],
    samsung: ['Galaxy S23', 'Galaxy Z Flip', 'Galaxy S22', 'Galaxy Note'],
    huawei: ['Mate 60', 'P60 Pro', 'Nova 11', 'Mate X3'],
    xiaomi: ['Xiaomi 13', 'Redmi Note 12', 'POCO F5', 'Black Shark 5'],
    default: ['Unknown brand, try: apple, samsung, huawei, xiaomi']
};

// 1. POST请求方式获取手机列表
app.post('/getPhones', (req, res) => {
    const { type } = req.body;

    if (!type) {
        return res.status(400).json({ error: 'Type is required' });
    }

    const phones = phoneDatabase[type.toLowerCase()] || phoneDatabase.default;
    res.json({ brand: type, phones });
});

// 2. GET请求方式获取手机列表
app.get('/phones', (req, res) => {
    const { brand } = req.query;

    if (!brand) {
        return res.status(400).json({ error: 'Brand is required (e.g., /phones?brand=apple)' });
    }

    const phones = phoneDatabase[brand.toLowerCase()] || phoneDatabase.default;
    res.json({ brand: brand, phones });
});

// 3. 获取所有品牌
app.get('/brands', (req, res) => {
    const brands = Object.keys(phoneDatabase).filter(brand => brand !== 'default');
    res.json({ brands });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`📱 手机API服务运行在: http://localhost:${PORT}`);
});
app.listen(3000, '0.0.0.0')   // 原来是 localhost